<?php

class WordsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','getstat','ajaxgetstat'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','admin','updatee','autocompletecountry','autocompletecity','autocompleteregion','upload'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$range = date("01/m/Y")." - ".date("d/m/Y"); 
		$this->render('view', array('model'=>$model, 'range'=>$range));		
	}
	
	// ajax statistic
	public function actionAjaxgetstat()
	{
		$rel = Yii::app()->request->getPost('rel');
		$range = Yii::app()->request->getPost('range');
		if ($rel && $range) { $result = $this->actionGetstat($rel, $range);	}
		header('Content-type: application/json');
		echo $result;
	}	
	
	// get statistic
	public function actionGetstat($rel, $date_range)
	{		
		$range = explode("-", $date_range);
		$startdate = trim($range[0]);
		$enddate = trim($range[1]);
		
		if ($rel && $range) {
			$modelshow = Statistic::model()->findAllByAttributes(
				array('rel'=>$rel, 'type'=>'show'),
				array(
					'condition'=>'date >= :startdate AND date <= :enddate', 
					'params'=>array(':startdate'=>$startdate,':enddate'=>$enddate)		
				)
			);	

			$modelclick = Statistic::model()->findAllByAttributes(
				array('rel'=>$rel, 'type'=>'click'),
				array(
					'condition'=>'date >= :startdate AND date <= :enddate', 
					'params'=>array(':startdate'=>$startdate,':enddate'=>$enddate)	
				)
			);	
		}

		$show = $modelshow ? count($modelshow) : "";
		$click = $modelclick ? count($modelclick) : "";
		
		$iResult = array('show'=>$show, 'click'=>$click);
		$aResult = array('result' => $iResult);
		return json_encode($aResult);
	}	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new Words;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Words']))
		{
			$model->attributes=$_POST['Words'];
			
			$model->source = date("Y-m-d-H-i-s");
			
			if ($model->type == 'video' && $model->source_vid) {
				$svideoscr = CUploadedFile::getInstance($model,'screen_vid_f');
				if (is_object($svideoscr) && get_class($svideoscr)==='CUploadedFile') {	$model->screen_vid = $svideoscr; }		
			}
				
			if($model->save()) 
			{
				if ($model->type == 'video') { if (is_object($model->screen_vid_f)) { $model->screen_vid_f->saveAs(Yii::getPathOfAlias('webroot.images.files').'/'.$model->screen_vid_f); } }
						
				if (!$this->generateHtml($model)) { print("Error generateHtml"); }
				$this->generateXML();
			
				if(Yii::app()->request->isAjaxRequest) { echo $model->source; Yii::app()->end(); }
				else { $this->redirect(array('/words/admin')); }					
			}
			else { print_r($model->getErrors()); }		
		}
		$this->render('create',array('model'=>$model)); 
	}	
	
	public function actionUpload()
    {
        $directory = Yii::getPathOfAlias('webroot.images.files') . '/';
		
        $filename = md5(date('YmdHis')).'.'.pathinfo(@$_FILES['file']['name'], PATHINFO_EXTENSION);
        
        if (move_uploaded_file(@$_FILES['file']['tmp_name'], $directory.$filename)) {
			$file = array('filelink' => 'images/files/'.$filename);
        }
		
		echo CJSON::encode($file);	
		Yii::app()->end();		
    } 		
	 
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Words']))
		{
			$model->attributes=$_POST['Words'];
	
			if (!$model->source) { $model->source = date("Y-m-d-H-i-s"); }
			
			if ($model->type == 'link') {
				
				$model->source_ban = "";
				$model->width_ban = "";
				$model->height_ban = "";
				$model->theme_ban = "default";
				$model->need_to_close_ban = "0";
				$model->show_header_ban = "0";
				$model->caption_ban = "";
				$model->ccap_ban = "";
				$model->show_footer_ban = "0";
				$model->footer_ban = "";
				$model->cfoot_ban = "";
				
				$model->screen_vid = "";
				$model->source_vid = "";
				$model->width_vid = "";
				$model->height_vid = "";
				$model->ap_vid = "0";
				$model->theme_vid = "default";
				$model->need_to_close_vid = "";
				$model->show_header_vid = "0";
				$model->caption_vid = "";
				$model->ccap_vid = "";
				$model->show_footer_vid = "0";
				$model->footer_vid = "";
				$model->cfoot_vid = "";
				
			}
			
			if ($model->type == 'banner' && $model->source_ban) {
				$model->screen_vid = "";
				$model->source_vid = "";
				$model->width_vid = "";
				$model->height_vid = "";
				$model->ap_vid = "0";
				$model->theme_vid = "default";
				$model->need_to_close_vid = "";
				$model->show_header_vid = "0";
				$model->caption_vid = "";
				$model->ccap_vid = "";
				$model->show_footer_vid = "0";
				$model->footer_vid = "";
				$model->cfoot_vid = "";				
			}
			
			if ($model->type == 'video' && $model->source_vid) {
				$svideoscr = CUploadedFile::getInstance($model,'screen_vid_f');
				if (is_object($svideoscr) && get_class($svideoscr)==='CUploadedFile') {	$model->screen_vid = $svideoscr; } 
				else { $model->screen_vid_f = ""; }
				$model->source_ban = "";
				$model->width_ban = "";
				$model->height_ban = "";
				$model->theme_ban = "default";
				$model->need_to_close_ban = "0";
				$model->show_header_ban = "0";
				$model->caption_ban = "";
				$model->ccap_ban = "";
				$model->show_footer_ban = "0";
				$model->footer_ban = "";
				$model->cfoot_ban = "";				
			}
		
			if($model->save()) {
				if ($model->type == 'video') { if ($svideoscr) { $svideoscr->saveAs(Yii::getPathOfAlias('webroot.images.files').'/'.$model->screen_vid); } }			
				if (!$this->generateHtml($model)) { print("Error generateHtml"); }
				$this->generateXML();
				$this->cleaner();
				
				if(Yii::app()->request->isAjaxRequest) { echo $model->source; Yii::app()->end(); }
				else { $this->redirect(array('/words/admin')); }				
				
			}
			else { print_r($model->getErrors()); }
		}

		$this->render('update',array('model'=>$model)); 
	}
	
	public function generateHtml($vmodel) 
	{
		$html = "";
		$footer = "";
		$result = true;
		$p = array("<p>","</p>","<p");
		$span = array("<span>","</span>","<span");		
		$div = array("<div>","</div>","<div");
		$closeb = "<div class=\"cluetip-close\"><a id=\"close\" href=\"javascript:void(0)\"><img width=\"18\" height=\"18\" title=\"Закрыть\" alt=\"\" src=\"http://www.elcp.ru/mon/images/banners/cross.png\"></a></div>';";
		$url = "http://www.elcp.ru/mon/";
		
		switch ($vmodel->type) {
			case "link": 
				break;
				
			case "banner": 
				$html .= '<script type="text/javascript">'."\n";
				
				if ($vmodel->theme_ban=="#123456") { $html .= 'var cluetipClass="'.$vmodel->source.'";'."\n"; $cls_ft_ban = $vmodel->source; $c_ban = ""; }
				else if ($vmodel->theme_ban=="#654321") { $html .= 'var cluetipClass="jtip";'."\n"; $cls_ft_ban = "jtip"; $c_ban = ""; }
				else if ($vmodel->theme_ban=="#654320") { $html .= 'var cluetipClass="gradient";'."\n"; $cls_ft_ban = "gradient"; $c_ban = ""; }
				else { $html .= 'var cluetipClass="default";'."\n"; $c_ban = $vmodel->theme_ban; $cls_ft_ban = "default"; }
				
				$html .= 'var caption_bg="'.$vmodel->ccap_ban.'";'."\n";
				$html .= 'var win_bg="'.$c_ban.'";'."\n";
				
				$html .= 'var ntoc="'.$vmodel->need_to_close_ban.'";'."\n";
				
				if ($vmodel->need_to_close_ban == "1") { $html .= $vmodel->caption_ban ? trim(preg_replace('/\s+/',' ',"var caption='".str_replace($p, $span, $vmodel->caption_ban)."".$closeb)) : "var caption='".$closeb.""; }
				else { $html .= $vmodel->caption_ban ? trim(preg_replace('/\s+/',' ',"var caption='<span>".str_replace($p, $div, $vmodel->caption_ban)."</span>';")) : "var caption=\"<i>\";"; }				
				$html .= "\n"."</script>"."\n";
				
				$c_ft_ban = $vmodel->cfoot_ban ? 'style="background-color:'.$vmodel->cfoot_ban.'"' : "";
				$footer = $vmodel->footer_ban ? '<div class="cluetip-'.$cls_ft_ban.'-toolbar" '.$c_ft_ban.'><span>'.str_replace($p, $div, $vmodel->footer_ban).'</span></div>' : ""; 
				
				$html .= '<div id="cluetip-inner">';
				if ($vmodel->source_ban) {
					preg_match('/src="([^"]*)"/i', $vmodel->source_ban, $array);
					if (preg_match("/.swf/i", $array[1])) {
						$html .= '<embed src="'.$url.$array[1].'" width="'.$vmodel->width_ban.'" height="'.$vmodel->height_ban.'" allowFullScreen="true" bgcolor="#000" name="fullscreen" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
					} else { $html .= strpos($array[1],'www') ? '<div><img src="'.$array[1].'"></div>' : '<div><img src="'.$url.$array[1].'"></div>'; }
				}				
				$html .= '</div>'.$footer;
				break; 
				
			case "video": 
				$html .= '<script type="text/javascript">'."\n";
				
				if ($vmodel->theme_vid=="#123456") { $html .= 'var cluetipClass="'.$vmodel->source.'";'."\n"; $cls_ft_vid = $vmodel->source; $c_vid = ""; }
				else if ($vmodel->theme_vid=="#654321") { $html .= 'var cluetipClass="jtip";'."\n"; $cls_ft_vid = "jtip"; $c_vid = ""; }
				else { $html .= 'var cluetipClass="default";'."\n";	$c_vid = $vmodel->theme_vid; $cls_ft_vid = "default"; }
				
				$html .= 'var caption_bg="'.$vmodel->ccap_vid.'";'."\n";
				$html .= 'var win_bg="'.$c_vid.'";'."\n";
				
				$html .= 'var ntoc="'.$vmodel->need_to_close_vid.'";'."\n";
				
				if ($vmodel->need_to_close_vid == "1") { $html .= $vmodel->caption_vid ? trim(preg_replace('/\s+/',' ',"var caption='".str_replace($p, $span, $vmodel->caption_vid)."".$closeb)) : "var caption='".$closeb.""; }
				else { $html .= $vmodel->caption_vid ? trim(preg_replace('/\s+/',' ',"var caption='<span>".str_replace($p, $div, $vmodel->caption_vid)."</span>';")) : "var caption=\"<i>\";"; } 
				$html .= "\n"."</script>"."\n";
				
				$c_ft_vid = $vmodel->cfoot_vid ? 'style="background-color:'.$vmodel->cfoot_vid.'"' : "";
				$footer = $vmodel->footer_vid ? '<div class="cluetip-'.$cls_ft_vid.'-toolbar" '.$c_ft_vid.'><span>'.str_replace($p, $div, $vmodel->footer_vid).'</span></div>' : "";
				
				$html .= '<div id="cluetip-inner">';
				if ($vmodel->source_vid) {
					$w = $vmodel->width_vid ? $vmodel->width_vid : "350"; $h = $vmodel->height_vid ? $vmodel->height_vid : "250";			
					preg_match('/href="([^\s"]+)/', $vmodel->source_vid, $match);
					if ($match) {
						if ($match[1] && preg_match("/.mp4/i", $match[1]) || preg_match("/.flv/i", $match[1])) {
							$html .= '<object type="application/x-shockwave-flash" data="'.$url.'images/banners/player_flv_multi.swf" width="'.$w.'" height="'.$h.'"><param name="movie" value="player_flv_multi.swf" /><param name="allowfullscreen" value="true" /><param name="flashvars" value="flv='.$url.$match[1].'&amp;showstop=1&amp;showvolume=1&amp;showtime=1&amp;showopen=0&amp;showfullscreen=1&amp;autoplay='.$vmodel->ap_vid.'&amp;startimage='.$url.'images/files/'.$vmodel->screen_vid.'" /></object>';
						}
						else { if ($match[1] && preg_match("/.webm/i", $match[1])) { $html .= '<iframe width="'.$w.'" height="'.$h.'" src="'.$match[1].'" frameborder="0" allowfullscreen></iframe>'; } }
					}
					else {
						$yid = $this->youtube_id_from_url($vmodel->source_vid);
						if ($yid) { 
							$srcv = "http://www.youtube.com/v/".$yid."?autoplay=".$vmodel->ap_vid;
							$html .= '<embed height="'.$h.'" width="'.$w.'" wmode="transparent" pluginspage="http://www.adobe.com/go/getflashplayer" src="'.$srcv.'" type="application/x-shockwave-flash" />';
						}
						else { 
							$vid = $this->vimeo_id_from_url($vmodel->source_vid);
							if ($vid) { 
								$srcvm = "//player.vimeo.com/video/".$vid;
								$html .= '<iframe src="'.$srcvm.'?autoplay='.$vmodel->ap_vid.'" width="'.$w.'" height="'.$h.'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
							}
						}
					}
				}				
				$html .= '</div>'.$footer;
				break;					
		}
		if ($html) {
			$file = Yii::getPathOfAlias('webroot.images.uploads').'/'.$vmodel->source.".html";
			file_put_contents($file, $html); 
		}
		return $result;
	}
	
	function youtube_id_from_url($url) 
	{
		$pattern = 
			'%^				# Match any youtube URL
			(?:https?://)?  # Optional scheme. Either http or https
			(?:www\.)?      # Optional www subdomain
			(?:             # Group host alternatives
			  youtu\.be/    # Either youtu.be,
			| youtube\.com  # or youtube.com
			  (?:           # Group path alternatives
				/embed/     # Either /embed/
			  | /v/         # or /v/
			  | /watch\?v=  # or /watch\?v=
			  )             # End path alternatives.
			)               # End host alternatives.
			([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
			$%x';
		$result = preg_match($pattern, $url, $matches);
		if (false !== $result) {
			if ($matches) { return $matches[1]; }
		}
		return false;
	}	
	
	function vimeo_id_from_url($url) 
	{
		$pattern = '#vimeo\.com\/(?P<id>[0-9]*)[\/\?]?#i';
		$result = preg_match($pattern, $url, $matches);
		if (false !== $result) {
			if ($matches) { return $matches[1]; }
		}
		return false;
	}	
	
	public function cleaner() {
		$sql = "SELECT * FROM tbl_words";
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql);
		$dataReader = $command->query();
		$rows = $dataReader->readAll();
		$list = Array();
		
		foreach ($rows as $v) 
		{
			preg_match('/href="([^\s"]+)/', $v['source_vid'], $href);
			if ($href) { $list[] = Yii::getPathOfAlias('webroot').'/'.$href[1]; }

			preg_match('/src="([^\s"]+)/', $v['source_ban'], $src);
			if ($src) { $list[] = Yii::getPathOfAlias('webroot').'/'.$src[1]; }
			
			if ($v['screen_vid']) { $list[] = Yii::getPathOfAlias('webroot')."/images/files/".$v['screen_vid']; }
		}
		
		$files = glob(Yii::getPathOfAlias('webroot')."/images/files/*.{jpg,png,gif,mp4}", GLOB_BRACE);
		
		$del[] = array_values(array_diff($files, $list));
	
		foreach ($del as $d) {
			if ($d) {
				$str = $d[0];
				@unlink($d[0]);
			}
			//else { $str = serialize($del); }
		}
		
		//$file = Yii::getPathOfAlias('webroot.images.files').'/log.txt';
		//file_put_contents($file, serialize($list)); 
	}		

	public function generateXML() {
		$sql = "SELECT * FROM tbl_src";
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql);
		$dataReader = $command->query();
		$rows = $dataReader->readAll();
		
		$xml = new domdocument("1.0", "Windows-1251");
		$xml->formatOutput = true;
		
		$root = $xml->createElement("settings");
		$xml->appendChild($root);	
		
		foreach ($rows as $v) 
		{	
			$active_s = $xml->createElement("active");
			$activeText_s = $xml->createTextNode($v['active']);
			$active_s->appendChild($activeText_s);
			
			$d_start = $xml->createElement("d_start");
			$d_startText = $xml->createTextNode($v['d_start']);
			$d_start->appendChild($d_startText);						
			
			$d_end = $xml->createElement("d_end");
			$d_endText = $xml->createTextNode($v['d_end']);
			$d_end->appendChild($d_endText);	
			
			$src = $xml->createElement("src");
			$srcText = $xml->createTextNode($v['src']);
			$src->appendChild($srcText);		

			$site = $xml->createElement("site");
			$siteText = $xml->createTextNode($v['site']);
			$site->appendChild($siteText);
		
			$item = $xml->createElement("item");
			$item->appendChild($active_s);							
			$item->appendChild($d_start);							
			$item->appendChild($d_end);							
			$item->appendChild($src);
			$item->appendChild($site);						
			
			$sqlw = "SELECT * FROM tbl_words WHERE src='".$v['src']."'";
			$commandw = $connection->createCommand($sqlw);
			$dataReaderw = $commandw->query();
			$rowsw = $dataReaderw->readAll();	
			
			$key_words = $xml->createElement("key_words");
			
			foreach ($rowsw as $vw) 
			{								
				$active = $xml->createElement("active_w");
				$activeText = $xml->createTextNode($vw['active_w']);
				$active->appendChild($activeText);		

				$date_start = $xml->createElement("d_start_w");
				$date_startText = $xml->createTextNode($vw['d_start_w']);
				$date_start->appendChild($date_startText);							
				
				$date_end = $xml->createElement("d_end_w");
				$date_endText = $xml->createTextNode($vw['d_end_w']);
				$date_end->appendChild($date_endText);	

				$country = $xml->createElement("country");
				$countryText = $xml->createTextNode($vw['country']);
				$country->appendChild($countryText);		

				$region = $xml->createElement("region");
				$regionText = $xml->createTextNode($vw['region']);
				$region->appendChild($regionText);	
				
				$city = $xml->createElement("city");
				$cityText = $xml->createTextNode($vw['city']);
				$city->appendChild($cityText);				
				
				$geo_inv = $xml->createElement("geot_invert");
				$geo_invText = $xml->createTextNode($vw['geot_invert'] == '0' ? "" : $vw['geot_invert']);
				$geo_inv->appendChild($geo_invText);									

				$title = $xml->createElement("title");
				$titleText = $xml->createTextNode($vw['title']);
				$title->appendChild($titleText);	
				
				$title_ex = $xml->createElement("title_ex");
				$titleText_ex = $xml->createTextNode($vw['title_ex']);
				$title_ex->appendChild($titleText_ex);					
				
				$type = $xml->createElement("type");
				$typeText = $xml->createTextNode($vw['type']);
				$type->appendChild($typeText);		

				$source = $xml->createElement("source");
				$sourceText = $xml->createTextNode($vw['source']);
				$source->appendChild($sourceText);					

				$target = $xml->createElement("target");
				$targetText = $xml->createTextNode($vw['target']);
				$target->appendChild($targetText);	

				$word = $xml->createElement("word");						
				$word->appendChild($active);	
				$word->appendChild($date_start);	
				$word->appendChild($date_end);	
				$word->appendChild($country);
				$word->appendChild($region);
				$word->appendChild($city);
				$word->appendChild($geo_inv);
				$word->appendChild($title);	
				$word->appendChild($title_ex);	
				$word->appendChild($type);	
				$word->appendChild($source);	
				$word->appendChild($target);	
				
				$key_words->appendChild($word);	
			}						
			$item->appendChild($key_words);		
			$root->appendChild($item);
		}	
		
		$fileContents = $xml->saveHTML();
        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $simpleXml = simplexml_load_string($fileContents);
        $json = json_encode($simpleXml);
		
		$file = Yii::getPathOfAlias('webroot.images.uploads').'/settings.json';
		file_put_contents($file, $json); 
		
		//$xml->save(Yii::getPathOfAlias('webroot.images.uploads').'/settings.xml');	
	}	
	
	public function actionUpdatee() 
	{	
		$es = new EditableSaver('Words'); 
		$es->update();	
		$this->generateXML();
	}	
	
	public function actionAutocompleteCountry() 
	{
        $termCountry = Yii::app()->getRequest()->getParam('term');

        if(Yii::app()->request->isAjaxRequest && $termCountry) {
            $criteriaCountry = new CDbCriteria;
            $criteriaCountry->addSearchCondition('name', $termCountry);
            $countries = Country::model()->findAll($criteriaCountry);
            $resultCountry = array();
            foreach($countries as $country) {
                $lableCountry = $country['name'];
                $resultCountry[] = array('id'=>$country['country_id'], 'label'=>$lableCountry, 'value'=>$lableCountry);
            }
            echo CJSON::encode($resultCountry);
            Yii::app()->end();
        }
    }
	
	public function actionAutocompleteCity() 
	{
        $termCity = Yii::app()->getRequest()->getParam('term');
		$country_id = Yii::app()->getRequest()->getParam('country_id');
		$region_id = Yii::app()->getRequest()->getParam('region_id');

        if(Yii::app()->request->isAjaxRequest && $termCity) {
            $criteriaCity = new CDbCriteria;
			if ($country_id) { $criteriaCity->addSearchCondition('country_id', $country_id); }
			if ($region_id) { $criteriaCity->addSearchCondition('region_id', $region_id); }			
            $criteriaCity->addSearchCondition('name', $termCity);
            $cities = City::model()->findAll($criteriaCity);
            $resultCity = array();
            foreach($cities as $city) {
                $lableCity = $city['name'];
                $resultCity[] = array('id'=>$city['city_id'], 'label'=>$lableCity, 'value'=>$lableCity);
            }
            echo CJSON::encode($resultCity);
            Yii::app()->end();
        }
    }	
	
	public function actionAutocompleteRegion() 
	{
        $termRegion = Yii::app()->getRequest()->getParam('term');
		$country_id = Yii::app()->getRequest()->getParam('country_id');

        if(Yii::app()->request->isAjaxRequest && $termRegion) {
            $criteriaRegion = new CDbCriteria;
			if ($country_id) { $criteriaRegion->addSearchCondition('country_id', $country_id); }
            $criteriaRegion->addSearchCondition('name', $termRegion);
            $regions = Region::model()->findAll($criteriaRegion);
            $resultRegion = array();
            foreach($regions as $region) {
                $lableRegion = $region['name'];
                $resultRegion[] = array('id'=>$region['region_id'], 'label'=>$lableRegion, 'value'=>$lableRegion);
            }
            echo CJSON::encode($resultRegion);
            Yii::app()->end();
        }
    }		

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
		
		$this->generateXML();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Words');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Words('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Words']))
			$model->attributes=$_GET['Words'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Words::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='words-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function checkResultType($data,$row)
	{
		$res = '';
		switch ($data->type) {
			case '':
				$res = "Выбрать";
				break;
			case 'link':
				$res = "Ссылка";
				break;
			case 'banner':
				$res = "Баннер";
				break;
			case 'video':
				$res = "Видео";
				break;				
		}
		return $res;
	}				
	
	protected function checkResultActivew($data,$row)
	{
		$res = '';
		switch ($data->active_w) {
			case '':
				$res = "Выбрать";
				break;
			case '1':
				$res = "Вкл.";
				break;
			case '0':
				$res = "Выкл.";
				break;								
		}
		return $res;
	}	
}
